import React, { useEffect, useRef } from 'react';
import { Chart } from '@antv/g2';
import { Card, Select, DatePicker, Space, Spin } from 'antd';
import { LineChartOutlined } from '@ant-design/icons';
import './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface ErrorTrendData {
  time: string;
  errorCount: number;
  errorRate: number;
  type: string;
}

interface ErrorTrendChartProps {
  data: ErrorTrendData[];
  loading?: boolean;
  height?: number;
  onTimeRangeChange?: (range: [string, string]) => void;
  onMetricChange?: (metric: string) => void;
}

const ErrorTrendChart: React.FC<ErrorTrendChartProps> = ({
  data,
  loading = false,
  height = 400,
  onTimeRangeChange,
  onMetricChange
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<Chart | null>(null);

  useEffect(() => {
    if (!chartRef.current || loading) return;

    // 销毁之前的图表实例
    if (chartInstance.current) {
      chartInstance.current.destroy();
    }

    // 创建新的图表实例
    const chart = new Chart({
      container: chartRef.current,
      autoFit: true,
      height,
      padding: [20, 40, 50, 60],
    });

    // 配置数据
    chart.data(data);

    // 配置比例尺
    chart.scale({
      time: {
        type: 'time',
        tickCount: 8,
        nice: true,
      },
      errorCount: {
        alias: '错误数量',
        nice: true,
      },
      errorRate: {
        alias: '错误率 (%)',
        nice: true,
        max: 100,
      },
    });

    // 配置坐标轴
    chart.axis('time', {
      title: {
        text: '时间',
        style: {
          fill: 'rgba(255, 255, 255, 0.8)',
          fontSize: 12,
        },
      },
      label: {
        style: {
          fill: 'rgba(255, 255, 255, 0.6)',
          fontSize: 11,
        },
        formatter: (text: string) => {
          const date = new Date(text);
          return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
        },
      },
      grid: {
        line: {
          style: {
            stroke: 'rgba(255, 255, 255, 0.1)',
            lineWidth: 1,
          },
        },
      },
    });

    chart.axis('errorCount', {
      title: {
        text: '错误数量',
        style: {
          fill: 'rgba(255, 255, 255, 0.8)',
          fontSize: 12,
        },
      },
      label: {
        style: {
          fill: 'rgba(255, 255, 255, 0.6)',
          fontSize: 11,
        },
      },
      grid: {
        line: {
          style: {
            stroke: 'rgba(255, 255, 255, 0.1)',
            lineWidth: 1,
          },
        },
      },
    });

    // 配置图例
    chart.legend({
      position: 'top',
      itemName: {
        style: {
          fill: 'rgba(255, 255, 255, 0.8)',
          fontSize: 12,
        },
      },
    });

    // 配置提示信息
    chart.tooltip({
      showCrosshairs: true,
      shared: true,
      crosshairs: {
        line: {
          style: {
            stroke: 'rgba(102, 126, 234, 0.6)',
            lineWidth: 1,
          },
        },
      },
      domStyles: {
        'g2-tooltip': {
          background: 'rgba(0, 0, 0, 0.8)',
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(255, 255, 255, 0.1)',
          borderRadius: '8px',
          color: 'rgba(255, 255, 255, 0.9)',
        },
      },
    });

    // 绘制错误数量折线图
    chart
      .line()
      .position('time*errorCount')
      .color('type', ['#667eea', '#764ba2'])
      .shape('smooth')
      .size(2)
      .style({
        shadowColor: 'rgba(102, 126, 234, 0.3)',
        shadowBlur: 10,
      });

    // 添加数据点
    chart
      .point()
      .position('time*errorCount')
      .color('type', ['#667eea', '#764ba2'])
      .size(4)
      .shape('circle')
      .style({
        fill: '#fff',
        stroke: '#667eea',
        lineWidth: 2,
        shadowColor: 'rgba(102, 126, 234, 0.5)',
        shadowBlur: 8,
      });

    // 添加面积填充
    chart
      .area()
      .position('time*errorCount')
      .color('type', [
        'l(90) 0:rgba(102, 126, 234, 0.1) 1:rgba(102, 126, 234, 0.3)',
        'l(90) 0:rgba(118, 75, 162, 0.1) 1:rgba(118, 75, 162, 0.3)',
      ])
      .shape('smooth');

    // 渲染图表
    chart.render();

    chartInstance.current = chart;

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [data, loading, height]);

  return (
    <Card
      className="error-trend-chart"
      title={
        <Space>
          <LineChartOutlined style={{ color: '#667eea' }} />
          <span>错误趋势分析</span>
        </Space>
      }
      extra={
        <Space>
          <Select
            defaultValue="errorCount"
            style={{ width: 120 }}
            onChange={onMetricChange}
            size="small"
          >
            <Option value="errorCount">错误数量</Option>
            <Option value="errorRate">错误率</Option>
            <Option value="both">双指标</Option>
          </Select>
          <RangePicker
            size="small"
            showTime
            onChange={(dates) => {
              if (dates && onTimeRangeChange) {
                onTimeRangeChange([
                  dates[0]?.format('YYYY-MM-DD HH:mm:ss') || '',
                  dates[1]?.format('YYYY-MM-DD HH:mm:ss') || '',
                ]);
              }
            }}
          />
        </Space>
      }
    >
      <Spin spinning={loading}>
        <div
          ref={chartRef}
          style={{
            width: '100%',
            height: `${height}px`,
            background: 'transparent',
          }}
        />
      </Spin>
    </Card>
  );
};

export default ErrorTrendChart;